<?php
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use app\admin\model\Article_CategoryModel;
use think\db\Where;
use think\Validate;

class Article_CategoryController extends AdminBaseController{
    public function index(){
        extract(input());
        $where = new Where;
        if(isset($category_name) && !empty($category_name)){
            $where['category_name'] = ['like','%'.$category_name.'%'];
        }
        $data = Article_CategoryModel::order('category_id Desc')->where($where)->paginate(3);
        $page = $data->render();
        return $this->fetch('',[
            'data' => $data,
            'page' => $page
        ]);
    }
    public function add() {
        return $this->fetch();
    }
    public function addPost() {
        $data = input();
        $rule = [
            'category_name' => 'require',
        ];
        $msg = [
            'category_name.require' => '请选择文章类别',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (true !== $result) {
            $this->error($validate->getError());
        }
        $add = Article_CategoryModel::create($data);
        if($add){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }
    public function edit(){
        $id = input('category_id');
        $data = Article_CategoryModel::where('category_id',$id)->find();
        $this->assign('data',$data);
        $this->assign('id',$id);
        return $this->fetch();
    }
    public function editPost(){
        $data = input();
        $rule = [
            'category_name'  => 'require',
        ];
        $msg = [
            'category_name.require' => '请选择文章类别',
        ];
        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);
        if (true!==$result){
            $this->error($validate->getError());
        }
        $edit = Article_CategoryModel::where('category_id',$data['category_id'])->update($data);
        if($edit){
            $this->success('修改成功','article_category/index');
        }else{
            $this->error('修改失败','article_category/index');
        }
    }
    public function delete () {
        $id = input('category_id');
        $del = Article_CategoryModel::where('category_id',$id)->delete();
        if($del){
            $this->success('删除成功','article_category/index');
        }else{
            $this->error('删除失败','article_category/index');
        }
    }
    public function delAll() {
        $ids = input('category_ids/a');
        $del = Article_CategoryModel::where('category_id',$ids)->delete($ids);
        if($del){
            $this->success('删除成功','article_category/index');
        }else{
            $this->error('删除失败','article_category/index');
        }
    }
}